package com.liuchang.exception;

import com.liuchang.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author :liuchang
 * @description:统一异常处理、数据预处理等
 * @date :2021/8/16 0:58
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * get参数校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result validExceptionHandler(BindException e) {
        Result result = new Result();
        LOG.warn("参数校验失败：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        result.setSuccess(false);
        result.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return result;
    }

    /**
     * post参数校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result validExceptionHandler(MethodArgumentNotValidException e) {
        LOG.warn("参数校验失败：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        Result result = new Result();
        result.setSuccess(false);
        result.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return result;
    }

    @ExceptionHandler(value = MyNullException.class)
    @ResponseBody
    public Result MyNullExceptionHandler(MyNullException e) {
        Result result = new Result();
        LOG.warn("操作异常：{}", "文件为空");
        result.setSuccess(false);
        result.setMessage("请传入文件");
        return result;
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result SystemExceptionHandler(Exception e) {
        Result result = new Result();
        LOG.error("系统异常：", e);
        result.setSuccess(false);
        result.setMessage("系统出现异常，请联系管理员");
        return result;
    }
}
